import igraph as ig
import matplotlib.pyplot as plt


def generate_dual_graph(original_graph):
    # 创建一个空的对偶图
    dual_graph = ig.Graph(directed=False)

    # 对于原始图中的每条边，在对偶图中创建一个对应的顶点
    num_edges = original_graph.ecount()  # 原始图的边数量
    dual_graph.add_vertices(num_edges)

    # 遍历原始图中的每个节点，检查该节点的相邻边
    original_vertex = []  # 存储每个对偶边所属的原始节点
    for vertex in range(original_graph.vcount()):
        incident_edges = original_graph.incident(vertex)  # 获取与当前顶点相连的所有边
        # 对于相邻的边对，在对偶图中添加对应的边
        for i in range(len(incident_edges)):
            for j in range(i + 1, len(incident_edges)):
                dual_graph.add_edge(incident_edges[i], incident_edges[j])
                original_vertex.append(vertex)

    dual_graph.es["ov"] = original_vertex
    return dual_graph


def draw_graph(graph: ig.Graph, layout="fr"):
    id_list = list(range(graph.vcount()))
    graph.vs["id"] = id_list
    id_list = list(range(graph.ecount()))
    graph.es["id"] = id_list
    fig, ax = plt.subplots(figsize=(10, 10))
    ig.plot(
        graph,
        target=ax,
        # layout="circle",
        layout=layout,
        vertex_size=0.3,
        # vertex_frame_width=4.0,
        vertex_color="lightblue",
        vertex_frame_color="white",
        vertex_label=graph.vs["id"],
        vertex_label_size=9.0,
        edge_color="gray",
        edge_label=graph.es["id"],
        edge_arrow_size=0.01,
        margin=40
    )
    plt.show()


def draw_graph_ov(graph: ig.Graph, layout="fr"):
    id_list = list(range(graph.vcount()))
    graph.vs["id"] = id_list
    fig, ax = plt.subplots(figsize=(10, 10))
    ig.plot(
        graph,
        target=ax,
        # layout="circle",
        layout=layout,
        vertex_size=0.3,
        # vertex_frame_width=4.0,
        vertex_color="lightblue",
        vertex_frame_color="white",
        vertex_label=graph.vs["id"],
        vertex_label_size=9.0,
        edge_color="gray",
        edge_label=graph.es["ov"],
        edge_arrow_size=0.01,
        margin=40
    )
    plt.show()
